import Compressor from 'compressorjs'
/**
 * 文件压缩
 * @param {*} file 压缩文件
 * @param {*} size 压缩至多少KB
 * @returns Promise
 */
export const compress = (file, size) => {
  const targetSize = size * 1024 // 1MB
  let quality = 0.8 // 初始压缩质量

  // 根据原始文件大小动态调整初始质量
  if (file.size > 5 * 1024 * 1024) {
    // 5MB以上
    quality = 0.4
  } else if (file.size > 3 * 1024 * 1024) {
    // 3-5MB
    quality = 0.5
  }

  const compressRecursively = (currentFile, currentQuality) => {
    return new Promise((resolve, reject) => {
      new Compressor(currentFile, {
        quality: currentQuality,
        convertSize: 500000,
        success(result) {
          if (result.size <= targetSize || currentQuality <= 0.1) {
            // 将压缩后的 Blob 转换为 File 对象（如果组件支持Blob则不用这一步）
            const compressedFile = new File([result], currentFile.name, {
              type: currentFile.type,
              lastModified: Date.now()
            })
            // alert(
            //   `最后压缩：压缩图片${parseInt(file.size / 1024)}KB至${parseInt(compressedFile.size / 1024)}KB 压缩比例${currentQuality}`
            // )
            resolve(compressedFile) // 达标或最低质量停止压缩
          } else {
            // 未达标则继续压缩（质量降低10%）
            compressRecursively(result, parseFloat((currentQuality - 0.1).toFixed(1)))
              .then(resolve)
              .catch(reject)
          }
        },
        error: (err) => {
          console.log(err.message)
          alert(err.message)
        }
      })
    })
  }

  return compressRecursively(file, quality)
}
